import { useRequest } from 'ahooks'
import { getQuestionInfoFun } from '../api/list'
import { useParams } from 'react-router-dom'
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { resertComponents } from '../store/componentsReducer'
import { pageInfoDefaultProps, resertPageInfo } from '../store/pageInfoReducer'

// 将查询问卷的功能单独抽离成一个单独的hooks，方便复用
export function useLoadQuestionData() {
  const { id } = useParams()
  const dispatch = useDispatch()

  const { run, loading, error } = useRequest(id => getQuestionInfoFun(id as string), {
    manual: true,
    onSuccess(res) {
      const { componentsList, title, description, jsCode, cssCode, publish, star } = res.data
      let selectedId = ''
      if (componentsList.length > 0) {
        selectedId = componentsList[0]._id
      }

      // 获取当前问卷对应的组件列表信息
      dispatch(resertComponents({ componentsList, selectedId }))
      // 获取页面配置信息
      dispatch(resertPageInfo({ title, description, jsCode, cssCode, publish, star }))
    }
  })

  useEffect(() => {
    if (id) {
      run(id)
    } else {
      dispatch(resertComponents({ componentsList: [], selectedId: '' }))
      dispatch(resertPageInfo(pageInfoDefaultProps))
    }
  }, [id])

  return {
    loading,
    error
  }
}
